Page({
    data: {
      userInfo: {
        phone: '138****1234',
        name: '张老师',
        position: '班主任',
        age: '35岁'
      },
      statsData: {
        todayTotal: 128,
        pending: 24,
        verifiedCount: 0
      },
      guardUserId: null
    },
    onLoad(options) {
      // 获取本地存储的门卫信息
      const guardUser = wx.getStorageSync('guardUser') || {};
      this.setData({
        userInfo: {
          phone: guardUser.phone || '',
          name: guardUser.name || '',
          position: guardUser.position || '',
          age: guardUser.age ? guardUser.age + '岁' : ''
        },
        guardUserId: guardUser.id || null
      });
      this.getVerifiedCount();
    },
    getVerifiedCount() {
      const guardUserId = this.data.guardUserId;
      if (!guardUserId) return;
      wx.request({
        url: getApp().globalData.baseUrl + '/api/visitor/scan_count',
        method: 'GET',
        data: { guard_user_id: guardUserId },
        success: (res) => {
          if (res.data.code === 200 && typeof res.data.data === 'number') {
            this.setData({ 'statsData.verifiedCount': res.data.data });
          }
        }
      });
    },
    onScan() {
      wx.scanCode({
        success: (res) => {
          // 假设二维码内容为访客id，或为json字符串包含visitor_id
          console.log(res);
          let visitor_id = null;
          try {
            const data = JSON.parse(res.result);
            visitor_id = data.visitor_id || data.id || data;
          } catch (e) {
            // 如果不是json，直接当作id
            visitor_id = res.result;
          }
          if (!visitor_id) {
            wx.showToast({ title: '二维码无效', icon: 'none' });
            return;
          }
          const guardUserId = this.data.guardUserId;
          if (!guardUserId) {
            wx.showToast({ title: '门卫信息缺失', icon: 'none' });
            return;
          }
          wx.request({
            url: getApp().globalData.baseUrl + '/api/visitor/scan_complete',
            method: 'POST',
            header: { 'content-type': 'application/json' },
            data: {
              visitor_id: Number(visitor_id),
              guard_user_id: Number(guardUserId)
            },
            success: (res) => {
              if (res.data.code === 200) {
                wx.showToast({ title: '核销成功', icon: 'success' });
              } else {
                wx.showToast({ title: res.data.msg || '核销失败', icon: 'none' });
              }
            },
            fail: () => {
              wx.showToast({ title: '网络错误', icon: 'none' });
            }
          });
        },
        fail: () => {
          wx.showToast({ title: '扫码失败', icon: 'none' });
        }
      });
    },
    onChangePassword() {
      wx.navigateTo({
        url: '/pages/changePassword/changePassword'
      });
    }
  });
  